'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
const CompressionWebpackPlugin = require('compression-webpack-plugin')

function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || '绿度银行管理平台'
const port = process.env.port || process.env.npm_config_port || 9528

module.exports = {
  publicPath: '/',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: false, // 禁用lint以提高构建速度
  productionSourceMap: false,
  
  css: {
    loaderOptions: {
      sass: {
        // 关键：指定用 dart-sass 编译（替代 node-sass）
        implementation: require('sass'),
        // 若项目有全局变量（如变量文件），继续保留原有配置（示例）
        // prependData: `@import "@/styles/variables.scss";`
      }
    }
  },
  
  devServer: {
    port: port,
    open: false, // 不自动打开浏览器以节省资源
    overlay: {
      warnings: false,
      errors: true
    },
    before: require('./mock/mock-server.js'),
    // 禁用热重载和实时重载以提高性能
    hot: false,
    liveReload: false
  },
  
  configureWebpack: {
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    plugins: [
      // 只在生产环境使用压缩插件
      ...(process.env.NODE_ENV === 'production' 
        ? [new CompressionWebpackPlugin({
            filename: '[path].gz[query]',
            algorithm: 'gzip',
            test: new RegExp('\\.(js|css)$'),
            threshold: 10240,
            minRatio: 0.8
          })]
        : []
      )
    ]
  },
  
  chainWebpack(config) {
    // 删除所有非必要的插件
    config.plugins.delete('preload')
    config.plugins.delete('prefetch')
    config.plugins.delete('fork-ts-checker')
    config.plugins.delete('friendly-errors')
    
    // 简化模块解析
    config.resolve.symlinks(false)
    
    // 禁用性能提示
    config.performance.hints(false)
    
    // 简化SVG处理
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
      
    // 开发环境配置
    config.when(process.env.NODE_ENV === 'development', config => {
      // 使用最简单的source map
      config.devtool('eval')
      // 最小化统计信息
      config.stats('errors-only')
    })
    
    // 生产环境下的优化配置
    config.when(process.env.NODE_ENV !== 'development', config => {
      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [{
          inline: /runtime\..*\.js$/
        }])
        .end()
      config
        .optimization.splitChunks({
          chunks: 'all',
          cacheGroups: {
            libs: {
              name: 'chunk-libs',
              test: /[\\/]node_modules[\\/]/,
              priority: 10,
              chunks: 'initial'
            },
            elementUI: {
              name: 'chunk-elementUI',
              priority: 20,
              test: /[\\/]node_modules[\\/]_?element-ui(.*)/
            },
            commons: {
              name: 'chunk-commons',
              test: resolve('src/components'),
              minChunks: 3,
              priority: 5,
              reuseExistingChunk: true
            }
          }
        })
      config.optimization.runtimeChunk('single')
    })
  }
}